package com.b2b.controller;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.b2b.exception.CustomException;
import com.b2b.model.common.ResponseBean;
import com.b2b.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping(value = "/fileUpload")
@CrossOrigin
@PropertySource("classpath:config.properties")
public class FileUploadController {
    //API密钥secretId
    @Value("${spring.qcloud.secretId}")
    private String secretId;
    //API密钥secretKey
    @Value("${spring.qcloud.secretKey}")
    private String secretKey;
    //存储桶所属地域
    @Value("${spring.qcloud.region}")
    private String region;
    //存储桶空间名称
    @Value("${spring.qcloud.bucketName}")
    private String bucketName;
    //存储桶访问域名
    @Value("${spring.qcloud.url}")
    private String url;
    //上传文件前缀路径(eg:/images/)
    @Value("${spring.qcloud.prefix}")
    private String prefix;

    private final FileUtil fileUtil;
    @Autowired
    public FileUploadController(FileUtil fileUtil){
        this.fileUtil = fileUtil;
    }

//    @RequestMapping(value = "/tengxun",method = RequestMethod.POST)
//    @ResponseBody
    @PostMapping("/img")
    public ResponseBean UploadImg(@RequestParam("file")MultipartFile file, HttpSession session){
        if(file == null){
            throw new CustomException("文件为空");
        }
        String oldFileName = file.getOriginalFilename();
        String eName = oldFileName.substring(oldFileName.lastIndexOf("."));
        if(!eName.equals(".jpg") && !eName.equals(".png")&& !eName.equals(".jpeg")&& !eName.equals(".gif")){
            throw new CustomException("文件格式错误(Update Failure)");
        }
        String newFileName = fileUtil.getFileName(oldFileName,eName);
        // 1 初始化用户身份信息(secretId, secretKey)
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        // 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        // 3 生成cos客户端
        COSClient cosclient = new COSClient(cred, clientConfig);
        // bucket的命名规则为{name}-{appid} ，此处填写的存储桶名称必须为此格式
        String bucketName = this.bucketName;

        // 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20 M 以下的文件使用该接口
        // 大文件上传请参照 API 文档高级 API 上传
        File localFile = null;
        try {
            localFile = File.createTempFile("temp",null);
            file.transferTo(localFile);
            // 指定要上传到 COS 上的路径
            String key = "/"+this.prefix+"/"+fileUtil.getFilePath()+newFileName;
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
            PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
            return new ResponseBean(HttpStatus.OK.value(), "上传成功(Upload Success)", this.url + putObjectRequest.getKey());
        } catch (IOException e) {
            return new ResponseBean(HttpStatus.OK.value(), e.getMessage(), null);
        }finally {
            // 关闭客户端(关闭后台线程)
            cosclient.shutdown();
        }
    }

    @PostMapping("/contract")
    public ResponseBean UploadContract(@RequestParam("file")MultipartFile file, HttpSession session){
        if(file == null){
            throw new CustomException("文件为空");
        }
        String oldFileName = file.getOriginalFilename();
        String eName = oldFileName.substring(oldFileName.lastIndexOf("."));
        if(!eName.equals(".doc") && !eName.equals(".pdf")&&!eName.equals(".docx")){
            throw new CustomException("文件格式错误(Update Failure)");
        }
        String newFileName = fileUtil.getFileName(oldFileName,eName);
        // 1 初始化用户身份信息(secretId, secretKey)
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        // 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        // 3 生成cos客户端
        COSClient cosclient = new COSClient(cred, clientConfig);
        // bucket的命名规则为{name}-{appid} ，此处填写的存储桶名称必须为此格式
        String bucketName = this.bucketName;

        // 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20 M 以下的文件使用该接口
        // 大文件上传请参照 API 文档高级 API 上传
        File localFile = null;
        try {
            localFile = File.createTempFile("temp",null);
            file.transferTo(localFile);
            // 指定要上传到 COS 上的路径
            String key = "/"+this.prefix+"/"+fileUtil.getFilePath()+newFileName;
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
            PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
            return new ResponseBean(HttpStatus.OK.value(), "上传成功(Upload Success)", this.url + putObjectRequest.getKey());
        } catch (IOException e) {
            return new ResponseBean(HttpStatus.OK.value(), e.getMessage(), null);
        }finally {
            // 关闭客户端(关闭后台线程)
            cosclient.shutdown();
        }
    }
}
